package com.herui.sdyu_lib.http.okhttp;

import com.herui.sdyu_lib.http.callback.Callback;
import com.herui.sdyu_lib.http.callback.Callback.*;
import com.herui.sdyu_lib.http.utils.HttpTool;
import com.herui.sdyu_lib.http.utils.Platform;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import okhttp3.Call;
import okhttp3.Response;

public class FileDownloadTask {

	private Callback.ProgressDownCallback<Void> callback;
	private Platform platform;
	private Call call;

	public FileDownloadTask(Call call, ProgressDownCallback<Void> callback, Platform platform) {
		super();
		this.call = call;
		this.callback = callback;
		this.platform = platform;
	}

	public void start() {
		HttpTool.executor.execute(new Runnable() {

			@Override
			public void run() {
				try {
					Response response = call.execute();
					long total = response.body().contentLength();
					saveFile(response);
				} catch (final IOException e) {
					e.printStackTrace();
					platform.execute(new Runnable() {
						public void run() {
							callback.onError(e, null, null);
						}
					});
				}
			}
		});
	}

	public String saveFile(Response response) throws IOException {
		InputStream is = null;
		byte[] buf = new byte[2048];
		int len = 0;
		FileOutputStream fos = null;
		try {
			is = response.body().byteStream();
			final long total = response.body().contentLength();
			long sum = 0;

			while ((len = is.read(buf)) != -1) {
				sum += len;

				System.out.println(sum + "----" + total);
			}

			return null;
		} finally {
			try {
				if (is != null) {
					is.close();
				}
			} catch (IOException e) {
			}
			try {
				if (fos != null) {
					fos.close();
				}
			} catch (IOException e) {
			}
		}
	}

}
